<template>
  <div class="reportDetailContainer">
    <div class="wrapper" id="wrapper">
      <!-- 头部 -->
      <van-nav-bar title="塔吊监测" left-arrow @click-left="onClickLeft">
      </van-nav-bar>
      <div class="wetherCont">
        <!-- 值 -->
        <div class="weather f fb">
          <div class="middleCont_left fl">
            <p class="top margin25">
              {{
                replaceEmpty(
                  !isNaN(summary.todayLoad) &&
                    Math.round(summary.todayLoad * 100) / 100,
                  "-"
                )
              }}
            </p>
            <p class="top1">今日载重</p>
            <p class="bot f fc">
              ({{ replaceEmpty(summary.liftingNumber, "-") }}次)
            </p>
          </div>
          <div class="middleCont_middle"></div>
          <div class="middleCont_left fl">
            <p class="top margin25">
              {{
                replaceEmpty(
                  !isNaN(summary.avgLoad) &&
                    Math.round(summary.avgLoad * 100) / 100,
                  "-"
                )
              }}
            </p>
            <p class="top1">日均载重</p>
            <p class="bot f fc">
              ({{
                replaceEmpty(
                  summary.avgLiftingNumber &&
                    Math.round(summary.avgLiftingNumber),
                  "-"
                )
              }}次)
            </p>
          </div>
          <div class="middleCont_middle"></div>
          <div class="middleCont_left fl">
            <p class="top margin25">
              {{
                replaceEmpty(
                  !isNaN(summary.countLoad) &&
                    Math.round(summary.countLoad * 100) / 100,
                  "-"
                )
              }}
            </p>
            <p class="top1">累计载重</p>
            <p class="bot f fc">
              ({{ replaceEmpty(summary.countLiftingNumber, "-") }}次)
            </p>
          </div>
        </div>
      </div>

      <div class="reportCont reportCont1">
        <!-- 预警 -->
        <div class="yujin">
          <div class="contTitle f fs">
            <van-icon name="arrow" class="right" />预警
          </div>
          <div class="weather f fb">
            <div class="middleCont_left fl">
              <p>
                今日: <span>{{ replaceEmpty(summary.warnCount, "-") }}</span>
              </p>
            </div>
            <div class="middleCont_middle"></div>
            <div class="middleCont_left fl">
              <p>
                开工累计:
                <span>{{ replaceEmpty(summary.totalWarn, "-") }}</span>
              </p>
            </div>
          </div>
        </div>
        <!-- 环境评价 -->
        <div class="hjpj">
          <div class="top f fb">
            <div class="left fl">
              <ul class="title_ul f">
                <li
                  class="title_li"
                  v-for="(item, index) in towerCraneList"
                  :key="index"
                  :class="{ title_li_act: titleIndex == index }"
                  @click="titleTap(index)"
                >
                  {{ item.craneName }}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <div class="lineH">
        <!-- 实时监测 -->
        <div class="towercont">
          <div class="contTitle f fb">
            <p class="title">实时监测</p>
            <p class="data f fc" @click="toHistory">历史数据</p>
          </div>
          <ul class="tower_ul">
            <li
              class="tower_li f fb"
              v-for="(item, index) in inspectParams"
              :key="index"
            >
              <div class="left f fc">{{ judgeProgressStyle(item).text }}</div>
              <div class="right fl">
                <div class="top f fb">
                  <span
                    >{{ item.name || ""
                    }}{{
                      `${replaceEmpty(item.range[0], "-")} ${item.unit}`
                    }}</span
                  >
                  <span>{{
                    `${replaceEmpty(item.range[1], "-")} ${item.unit}`
                  }}</span>
                </div>
                <!-- <el-progress
                  :status="
                    judgeProgressStyle(item).percent >= 100
                      ? 'exception'
                      : 'active'
                  "
                  :percent="judgeProgressStyle(item).percent"
                  :strokeWidth="12"
                  :strokeColor="judgeProgressStyle(item).color"
                ></el-progress> -->
                <el-progress
                  :text-inside="true"
                  :percentage="item.value"
                  :strokeWidth="20"
                  color="#1AAB03"
                ></el-progress>
              </div>
            </li>
          </ul>
        </div>
        <!-- 视频 -->
        <div class="towercont">
          <div class="vedio">
            <myVideo
              v-if="
                towerCraneList[titleIndex] &&
                towerCraneList[titleIndex].monitorVideoUrl
              "
              class="vedioa"
              id="vd"
              ref="video"
              :url="towerCraneList[titleIndex].monitorVideoUrl"
            />
          </div>
        </div>
        <!-- 作业人员 -->
        <div class="towercont">
          <div class="towerPerson f vfs">
            <div class="left">
              <div class="grzp">
                <img :src="openInfo.photo?openInfo.photo:nodata" alt="" />
              </div>
              <p>姓名：{{ replaceEmpty(openInfo.staffName, "-") }}</p>
              <p>打卡时间：{{ replaceEmpty(openInfo.punchTime, "-") }}</p>
              <p>
                连续工作时长：
                {{
                  openInfo.workingHours >= 0
                    ? openInfo.workingHours > 0
                      ? openInfo.workingHours + "小时"
                      : openInfo.workingMinute + "分钟"
                    : (openInfo.punchTime &&
                        moment(openInfo.punchTime).fromNow(true)) ||
                      "-"
                }}
              </p>
              <p>联系方式：{{ replaceEmpty(openInfo.mobile, "-") }}</p>
            </div>
            <div class="left">
              <div class="tzzg">
                <img
               
                  :src="openInfo.specialCardImg?openInfo.specialCardImg:nodata"
                  alt=""
                />
              </div>

              <p>
                特种作业资格证：{{ replaceEmpty(openInfo.specialCardNo, "-") }}
              </p>
              <p>
                有效期至：{{
                  replaceEmpty(
                    openInfo.useTime && openInfo.useTime.slice(0, 10),
                    "-"
                  )
                }}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
var projectId = localStorage.getItem("projectid");
import {
  collectCranBase,
  infoCranBase,
  queryCranBaseByPCid,
  craneInfoOpen,
  subscriptionPost,
  
} from "@/api/api";
//websocket
import SockJS from "sockjs-client";
import Stomp from "stompjs";
const baseURL = "http://39.108.81.42:9080"; // 正式服地址
import myVideo from "../vedioCommon.vue";
export default {
  components: {
    myVideo,
  },
  data() {
    return {
      //日历
   nodata: require("../../imgs/nodata.png"),
      titleIndex: 0,
      //面板实测
      summary: {},
      //塔吊信息
      towerCraneList: [],
      //载重啥的
      inspectParams: [
        {
          name: "载重",
          value: undefined,
          range: [undefined, undefined],
          unit: "t",
          limit: [undefined, undefined],
        },
        {
          name: "幅度",
          value: undefined,
          range: [undefined, undefined],
          unit: "m",
          limit: [undefined, undefined],
        },
        {
          name: "力矩",
          value: undefined,
          range: [undefined, undefined],
          unit: "kN·m",
          limit: [undefined, undefined],
        },
        {
          name: "高度",
          value: undefined,
          range: [undefined, undefined],
          unit: "m",
          limit: [undefined, undefined],
        },
        {
          name: "倾角",
          value: undefined,
          range: [undefined, undefined],
          unit: "°",
          limit: [undefined, undefined],
        },
        {
          name: "风速",
          value: undefined,
          range: [undefined, undefined],
          unit: "m/s",
          limit: [undefined, undefined],
        },
      ],
      creanceId: "",
      openInfo: {},
          realData: [],
    };
  },
  mounted() {
    this.init();
    this.subscriptionPost1();
  },
    watch: {
    creanceId: function (newVal, oldVal) {
      // TO DO
      var that = this;
      if (that.realData.length > 0) {
        var v = this.realData;
        v.forEach((obj) => {
          if (parseInt(obj.creanceId) == newVal) {
            that.inspectParams[0].value = obj.craneLoad;
            // 楼层
            that.inspectParams[1].value = obj.radius;
            // 楼层
            that.inspectParams[2].value = obj.ratedKn;
            // 速度
            that.inspectParams[3].value = obj.height;
            // 倾角
            that.inspectParams[4].value = obj.angle;
            // 风速
            that.inspectParams[5].value = obj.windSpeed || 0;
            // that.paintChart_1(obj.body);
          }
        });
      }
    },
  },
  methods: {
    
    init() {
      //面板实测值
      this.Request(infoCranBase(projectId)).then((res) => {
        if (res.status == "200") {
          this.summary = res.body;
        } else {
          this.$message({
            type: "error",
            message: res.message,
            center: "true",
          });
        }
      });
      //塔吊信息
      this.Request(queryCranBaseByPCid(projectId)).then((res) => {
        if (res.status == "200") {
          this.towerCraneList = res.body;
          res.body.length && this.titleTap(0);
          this.creanceId = this.towerCraneList[0].creanceId;
          this.craneInfoOpen1();
        } else {
          this.$message({
            type: "error",
            message: res.message,
            center: "true",
          });
        }
      });
    },
    subscriptionPost1() {
      this.Request(subscriptionPost(projectId)).then((res) => {
        if (res.status == "200") {
          this.initWebSocket(res.body);
        } else {
          this.$message({
            type: "error",
            message: res.message,
            center: "true",
          });
        }
      });
    },
    //实时监测数据
    initWebSocket(data) {
      // debugger;
      var that = this;
      const user = /39\.108/.test(baseURL)
        ? {
            userName: "pm_consume",
            userPassword: "123456",
            class: "vhost_01",
          }
        : {
            userName: "test",
            userPassword: "123456",
            class: "v_01",
          }; // 账号信息
      var datas = `/amq/queue/${data}`;
      // Stomp.js boilerplate
      // var client = Stomp.client("ws://192.168.1.127:15674/ws");
      const url = baseURL.replace("http", "ws").replace(/:\d+/, ":15674");
      var client = Stomp.client(`${url}/ws`);
      console.log("client", client);
       client.debug = null; // 不打印日志
      // 收入信息
      var on_connect = function (x) {
        client.subscribe(datas, function (d) {
          var obj = JSON.parse(d.body);
          if (obj.type === "REAL_DATA_CRANE") {
            console.log("REAL_DATA_CRANE", obj);
            that.realData.push(obj.body);
            if (parseInt(obj.body.creanceId) == that.creanceId) {
              that.inspectParams[0].value = obj.body.craneLoad;
              // 楼层
              that.inspectParams[1].value = obj.body.radius;
              // 楼层
              that.inspectParams[2].value = obj.body.ratedKn;
              // 速度
              that.inspectParams[3].value = obj.body.height;
              // 倾角
              that.inspectParams[4].value = obj.body.angle;
              // 风速
              that.inspectParams[5].value = obj.body.windSpeed ;
              // that.paintChart_1(obj.body);
            }
          }
        });
      };
      // 失败
      var on_error = function () {
        console.log("验证MQ失败");
      };
      client.connect(
        user.userName,
        user.userPassword,
        on_connect,
        on_error,
        user.class
      );
    },
    //司机信息
    craneInfoOpen1() {
      var params = {
        projectId: projectId,
        creanceId: this.creanceId,
      };
      this.Request(craneInfoOpen(params)).then((res) => {
        if (res.status == "200") {
          this.openInfo = res.body;
        } else {
          this.$message({
            type: "error",
            message: res.message,
            center: "true",
          });
        }
      });
    },
    //给载重赋值
    setInspectBaseData(data = {}, i) {
      const {
        limitValue,
        maxAngle,
        maxCraneLoad,
        maxHeight,
        maxRadius,
        maxRatedKn,
        maxWindSpeed,
        minAngle,
        minCraneLoad,
        minHeight,
        minRadius,
        minRatedKn,
        minWindSpeed,
      } = data;
      const arr = [null, null, null, null, null, null];
      arr[0] = {
        name: "载重",
        value: this.inspectParams[0] && this.inspectParams[0].value,
        range: [minCraneLoad, maxCraneLoad],
        unit: "t",
        limit: [
          (limitValue / 100) * minCraneLoad,
          (limitValue / 100) * maxCraneLoad,
        ],
      };
      // 判断 实时刷新只要载重范围 其他只要基础数据 所以我 i 当是 true 是推送过来的数据，false 是页面请求 所以拦截
      //if (!i) {
      if (i) {
        arr[1] = {
          name: "幅度",
          value: this.inspectParams[1] && this.inspectParams[1].value,
          range: [minRadius, maxRadius],
          unit: "m",
          limit: [
            (limitValue / 100) * minRadius,
            (limitValue / 100) * maxRadius,
          ],
        };
        arr[2] = {
          name: "力矩",
          value: this.inspectParams[2] && this.inspectParams[2].value,
          range: [minRatedKn, maxRatedKn],
          unit: "kN·m",
          limit: [
            (limitValue / 100) * minRatedKn,
            (limitValue / 100) * maxRatedKn,
          ],
        };
        arr[3] = {
          name: "高度",
          value: this.inspectParams[3] && this.inspectParams[3].value,
          range: [minHeight, maxHeight],
          unit: "m",
          limit: [
            (limitValue / 100) * minHeight,
            (limitValue / 100) * maxHeight,
          ],
        };
        arr[4] = {
          name: "倾角",
          value: this.inspectParams[4] && this.inspectParams[4].value,
          range: [minAngle, maxAngle],
          unit: "°",
          limit: [(limitValue / 100) * minAngle, (limitValue / 100) * maxAngle],
        };
        arr[5] = {
          name: "风速",
          value: this.inspectParams[5] && this.inspectParams[5].value,
          range: [minWindSpeed, maxWindSpeed],
          unit: "m/s",
          limit: [
            (limitValue / 100) * minWindSpeed,
            (limitValue / 100) * maxWindSpeed,
          ],
        };

        this.inspectParams = arr;
      } else {
        this.inspectParams[0] = arr[0];
      }
    },
    //
    /**
     * 根据参数计算出相关属性
     * @param {number} precision 保留的精度（小数点后几位）
     * @param {object} 属性对象
     */
    judgeProgressStyle(inspectParam = {}, precision = 0) {
      const { value, limit } = inspectParam;
      const min = inspectParam.range[0];
      const max = inspectParam.range[1];
      const texts = ["正常", "超限", "~"];
      const classes = ["safe", "danger", "default"];
      const colors = ["#04BD70", "#E6392F", "#555"];
      // 0 正常， 1超， 2 无
      const judgeStatus =
        !isNaN(min) && !isNaN(max) && limit && limit.length === 2
          ? value < limit[0] || value > limit[1]
            ? 1
            : 0
          : 2;
      if (isNaN(value)) {
        return {
          text: "~",
          class: "default",
          color: "#ececec",
          percent: 0,
        };
      }
      const percent =
        (!isNaN(min) &&
          !isNaN(max) &&
          Math.round(((100 * (value - min)) / (max - min)) * 10 ** precision) /
            10 ** precision) ||
        0;
      return {
        text: texts[judgeStatus],
        class: classes[judgeStatus],
        color: colors[judgeStatus],
        percent,
      };
    },
    replaceEmpty(data, placeholder = "", maxLength) {
      if (data === null || data === undefined || data === false)
        return placeholder;
      if (maxLength) {
        return data.length > maxLength
          ? `${data.slice(0, maxLength)}...`
          : data;
      }
      return data;
    },
    onClickLeft() {
      this.$router.go(-1); //返回上一层
    },
    toHistory() {
      this.$router.push({path:'/towerCraneHistory'}); //返回上一层
    },
    
    //标题切换
    titleTap(index) {
      this.titleIndex = index;
      this.setInspectBaseData(this.towerCraneList[this.titleIndex], 1);
      this.creanceId = this.towerCraneList[this.titleIndex].creanceId;
      this.craneInfoOpen1();
    },
  },
};
</script>
<style lang="stylus" scoped>
@import '../../assets/common';
/deep/.el-progress-bar__innerText{
  color:#f00;
  font-size:24px;
}
.yujin {
  width: 100%;
  height: 164px;
  background: #FFFFFF;
  box-shadow: 0px 14px 16px 0px rgba(43, 102, 253, 0.07);
  border-radius: 5px;
  margin-bottom: 30px;

  .contTitle {
    width: 100%;
    height: 70px;
    font-size: 30px;
    font-family: Microsoft YaHei;
    font-weight: 600;
    color: #000000;
    padding-left: 20px;

    .right {
      color: #0084FF;
      font-size: 40px;
      font-weight: bold;
      margin-right: 14px;
    }
  }

  .weather {
    width: 100%;
    height: 70px;

    .middleCont_left {
      text-align: center;
      font-size: 24px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #282828;

      span {
        font-size: 36px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #0078CB;
        margin-left: 15px;
      }
    }

    .middleCont_middle {
      width: 1px;
      height: 70px;
      background: rgba(53, 146, 243, 0.47);
    }
  }
}

.wetherCont {
  width: 100%;
  height: 300px;
  background: url('../../imgs/reportBg.jpg') no-repeat;
  background-size: 100% 100%;
  padding: 30px 0;
  box-sizing: border-box;

  .weather {
    width: 93%;
    margin: 0 auto;
    padding: 0 30px;
    box-sizing: border-box;
    background: rgba(249, 255, 252, 0.2);
    border-radius: 8px;
    height: 180px;

    .middleCont_left {
      color: #fff;
      text-align: center;

      .top1 {
        font-size: 28px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #FFFFFF;
        margin-bottom: 25px;
      }

      .top {
        font-weight: bold;
        font-size: 36px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #F2FE31;
        margin-bottom: 24px;
      }

      .bot {
        font-size: 28px;
        color: rgba(255, 255, 255, 0.5);
      }
    }

    .middleCont_middle {
      width: 1px;
      height: 90px;
      background: #fff;
      opacity: 0.47;
      
    }
  }
}

.reportCont1 {
  height: auto !important;
  padding-bottom: 0 !important;
}

.lineH {
  width: 100%;
  height: calc(100% - 675px);
  overflow-y: scroll;
  box-sizing: border-box;

}

.towercont {
  width: 100%;
 
  box-sizing: border-box;
  border-left: 10px solid #0078CB;
  padding-left: 30px;
  background: #fff;
  margin-bottom: 30px;

  .contTitle {
    width: 100%;
    height: 70px;
    border-bottom: 1px solid rgba(40, 40, 40, 0.2);
    margin-bottom: 30px;
    

    .title {
      font-size: 30px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #0078CB;
    }

    .data {
      width: 137px;
      height: 55px;
      background: #0078CB;
      border-radius: 5px 0 0 5px;
      color: #FFFFFF;
      font-size: 28px;
    }
  }

  .tower_ul {
    width: 100%;
    padding-right: 30px;
    box-sizing: border-box;

    .tower_li {
      width: 100%;
      height: 130px;
      border-bottom: 1px solid rgba(40, 40, 40, 0.2);

      .left {
        width: 67px;
        height: 67px;
        border-radius: 100%;
        border: 4px solid #1AAB03;
        flex-shrink: 0;
        margin-right: 28px;
        color: #1AAB03;
      }

      .right {
        .top {
          margin-bottom: 10px;
        }
      }
    }
  }

  // 视频
  .vedio {
    width: 100%;
    padding: 30px 30px 30px 0;
    box-sizing: border-box;

    .vedioa {
      width: 100%;
      height: 290px;
    }
  }

  // 作业人员
  .towerPerson {
    width: 100%;
    padding: 30px 30px 30px 0;
    box-sizing: border-box;

    .left {
      width: 50%;
      text-align: center;

      .grzp {
        width: 183px;
        height: 198px;
        background: #ccc;
        margin-bottom: 10px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .tzzg {
        width: 320px;
        height: 198px;
        background: #ccc;
        margin-bottom: 10px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      p {
        text-align: left;
        margin-bottom: 15px;
      }

      font-size: 24px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #333333;
    }
  }
}
</style>